package com.bb.blog.code.mybatis.mapper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;

import java.util.Set;

public class MapperXPathMapperScanner extends ClassPathBeanDefinitionScanner {
    private Logger logger = LoggerFactory.getLogger(MapperXPathMapperScanner.class);
    public MapperXPathMapperScanner(BeanDefinitionRegistry registry) {
        super(registry);
    }


    public void registerFilters() {
//        addIncludeFilter(new AnnotationTypeFilter(Annotation.class));
        addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
    }


    @Override
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Set<BeanDefinitionHolder> beanDefinitionHolders =  super.doScan(basePackages);
        if(beanDefinitionHolders.isEmpty()){
            logger.info("NO MapperX was found ");
        }else{
            processBeanDefinitions(beanDefinitionHolders);
        }
        return beanDefinitionHolders;
    }

    private void processBeanDefinitions(Set<BeanDefinitionHolder> beanDefinitionHolders) {
        GenericBeanDefinition definition;

        for(BeanDefinitionHolder holder: beanDefinitionHolders){
            definition = (GenericBeanDefinition) holder.getBeanDefinition();
            String beanClassName = definition.getBeanClassName();
            logger.info("Creating MapperFactoryBean with name '" + holder.getBeanName() + "' and '" + beanClassName
                + "' mapperInterface");
            definition.getConstructorArgumentValues().addGenericArgumentValue(beanClassName);
            definition.setBeanClass(MapperXFactoryBean.class);
            definition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_TYPE);
//            definition.setLazyInit(true);
        }
    }

    @Override
    protected boolean isCandidateComponent(AnnotatedBeanDefinition beanDefinition) {
        return beanDefinition.getMetadata().isInterface() && beanDefinition.getMetadata().isIndependent();
    }
}
